from rest_framework import generics
from rest_framework.response import Response
from rest_framework import status
from apps.drf_test_5_二级视图.serializer import BookModelSerializer
from apps.drf_test_0Django原始restful.models import BookinfoModels


class BookGenericAPIView(generics.GenericAPIView):
    """
    二级视图类-列表视图
    """
    # 抽离公共模型对象
    queryset = BookinfoModels.objects.all()
    # 抽离公共序列化器
    serializer_class = BookModelSerializer

    def get(self,request):
        books = self.get_queryset()
        serializer = self.get_serializer(books,many=True)
        return Response(serializer.data,status=status.HTTP_200_OK)


    def post(self,request):
        res = request.data
        serializer = self.get_serializer(data=res)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data,status=status.HTTP_201_CREATED)


class BookDetialGenericAPIView(generics.GenericAPIView):
    """
    二级视图类-详情视图
    """
    queryset = BookinfoModels.objects.all()
    serializer_class = BookModelSerializer

    def get(self,request,pk):
        book = self.get_object()
        serializer = self.get_serializer(book)
        return Response(serializer.data,status=status.HTTP_200_OK)

    def put(self,request,pk):
        book = self.get_object()
        res = request.data
        serializer = self.get_serializer(instance=book,data=res)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data,status=status.HTTP_201_CREATED)

    def delete(self,request,pk):
        book = self.get_object()
        book.delete()
        return Response(status=status.HTTP_200_OK)






